Skip to content

SQL-496: Convert the function system tables to catalog views - #40900

Open
SangJunBak wants to merge 3 commits into
jun/sql-495/type-relationsfrom
jun/function-relations
Open

SangJunBak wants to merge 3 commits into
jun/sql-495/type-relationsfrom
jun/function-relations

Conversation

@SangJunBak

@SangJunBak SangJunBak commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

See commit messages for details.

Much of the data, other than the catalog IDs, come statically since we only have builtin functions. Before reviewing, I'd recommend reading https://claude.ai/artifact/D4cjDcAZj1BNEEi1FoAgVY?sk=OQFwpa83kcrWYEernXwqdw#bg-narrow to get a primer of what column represents.

Motivation

Closes SQL-496

Verification

  • Diffed the function relations against what's currently on main
  • Added SLTs for verifying certain properties across our function relations

@SangJunBak SangJunBak changed the title catalog: define the function and operator relations as views SQL-496: convert function and operator relations builtin tables Nov 18, 2026
@SangJunBak
SangJunBak added this pull request to stack #40899 November 18, 2026 07:57
@SangJunBak
SangJunBak force-pushed the jun/function-relations branch from 80fcf1c to 48b2111 Compare November 18, 2026 22:01
@SangJunBak
SangJunBak force-pushed the jun/function-relations branch from 48b2111 to 1023d89 Compare November 18, 2026 23:01
@SangJunBak SangJunBak changed the title SQL-496: convert function and operator relations builtin tables SQL-495: Convert the function system tables to catalog views Nov 18, 2026
@linear-code

linear-code Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

SQL-496

@SangJunBak
SangJunBak force-pushed the jun/function-relations branch from 1023d89 to caf16d7 Compare November 19, 2026 01:49
@SangJunBak
SangJunBak marked this pull request as ready for review November 19, 2026 01:53
@SangJunBak
SangJunBak requested review from a team as code owners November 19, 2026 01:53
@SangJunBak SangJunBak changed the title SQL-495: Convert the function system tables to catalog views SQL-496: Convert the function system tables to catalog views Nov 19, 2026
@def-

def- commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

QA LLM Review

1. MEDIUM -- Zero-argument functions disappear from arity-zero lookups

src/catalog/src/builtin/mz_catalog.rs:2792

After upgrade, WHERE array_length(argument_type_ids, 1) = 0 silently drops every zero-argument signature from mz_functions, including now(). The fallback changes the first dimension’s length from 0 to NULL as observed by SQL.

Details

The old row packer always supplied one dimension with length equal to the argument count. The SQL constructor for ARRAY[]::text[] supplies zero dimensions (src/expr/src/scalar/func.rs:2737), and array_length returns NULL for a missing dimension (src/expr/src/scalar/func.rs:2941). The assertion at test/sqllogictest/function_relations.slt:53 casts the array to text, which prints {} for either shape. Check the dimension length directly when preserving the old catalog value.

2. MEDIUM -- Small catalog reads now build a dataflow per request

src/catalog/src/builtin/mz_catalog.rs:2779

SELECT * FROM mz_functions LIMIT 1 previously qualified for a bounded persist peek. On the catalog server it now needs a temporary dataflow to resolve type IDs and assemble argument arrays before returning one row. Repeated catalog previews pay that setup cost on every request. The same regression applies to mz_operators.

Details

The former tables satisfied the unfiltered small-limit fast path at src/adapter/src/coord/peek.rs:602. The new views have indexes on their inputs only. Their plans join 937 function-argument rows or 674 operator-argument rows to type mappings and aggregate by OID (test/sqllogictest/catalog_server_explain.slt:9058 and test/sqllogictest/catalog_server_explain.slt:9211). A final limit cannot turn those joins into a peek. An index on each resolved view on the catalog server would let these reads reuse the assembled rows.

@ggevay ggevay left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some comments inline. The index one and the empty-array one are the important ones.

The description says Closes SQL-495, the title says SQL-496.

pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
BuiltinTable {
name: "mz_functions",
pub static MZ_FUNCTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The QA bot's second point is wider than LIMIT 1: every read of mz_functions, pg_proc or information_schema.routines now plans and optimizes this view. Medians of 11 runs on the CI images of 8f35c46 (before) and caf16d7 (after):

query before after after, with indexes
SELECT * FROM mz_functions 48 ms 116 ms 28 ms
SELECT oid FROM mz_functions WHERE name = 'now' 16 ms 100 ms 2.5 ms
SELECT proname FROM pg_proc WHERE oid = 1299 26 ms 140 ms 18 ms
SELECT count(*) FROM information_schema.routines 21 ms 124 ms 13 ms
SELECT * FROM mz_operators 42 ms 66 ms 23 ms
Npgsql's type-loading query 187 ms 392 ms 182 ms

The last row is the query that Npgsql (the .NET driver) sends when a client first connects. It joins pg_proc twice.

Could we add the indexes the bot suggests, on mz_functions and mz_operators in mz_catalog_server (as mz_types has mz_types_ind)? The last column is with such indexes created ad hoc. Together they hold about 0.3 MB.

Comment on lines +39 to +49
# Argument types resolve to mz_types ids in argument order.
query TT rowsort
SELECT a1.name, a2.name
FROM mz_functions f
JOIN mz_types a1 ON a1.id = f.argument_type_ids[1]
JOIN mz_types a2 ON a2.id = f.argument_type_ids[2]
WHERE f.name = 'date_trunc' AND array_length(f.argument_type_ids, 1) = 2
----
text interval
text timestamp
text timestamptz

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The join that resolves argument types depends on its object_type filter, because seven names are both a type and a function (date, daterange, ...). Without the filter, 6 rows of mz_functions get extra argument ids (max and min on date, daterange, extract, datediff), and every check in this file still passes. Maybe compare the argument counts with the generated view:

# Every implementation resolves each of its argument types to exactly one type.
query I
SELECT count(*)
FROM mz_functions f
JOIN mz_internal.mz_builtin_functions b USING (oid)
WHERE coalesce(array_length(f.argument_type_ids, 1), 0) != coalesce(array_length(b.argument_type_names, 1), 0)
----
0

(mz_operators has the same join, but there the pg_operator listing in pg_catalog_proc.slt would notice.)

fn type_name_sql(name: Option<&str>, type_names: &BTreeSet<&str>) -> String {
match name {
Some(name) => {
// Panic if

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfinished comment.

Comment on lines +135 to +138
// Tables, views, materialized views, indexes, types, functions
// and metric sinks are exposed through materialized views derived
// from `mz_catalog_raw`, and logs and secrets never had
// builtin-table rows, so none pack a row here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#40843 changed this to "relations derived from", and this goes back to "materialized views". The type and function relations are plain views now.

func.oid,
func_schema.id AS schema_id,
func.name,
COALESCE(args.argument_type_ids, ARRAY[]::text[]) AS argument_type_ids,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The QA bot's first point: for a function without arguments, array_length(argument_type_ids, 1) was 0 and is NULL now. PostgreSQL's pg_proc.proargtypes gives 0 for such functions too. Could this keep the old value? array_remove(ARRAY[NULL::text], NULL) as the fallback reproduces it. (The check on now in function_relations.slt casts to text, which prints {} for both.)

ggevay added a commit that referenced this pull request Nov 25, 2026
Closes: [SQL-948](https://linear.app/materializeinc/issue/SQL-948)

### Motivation

During a 0dt upgrade, a builtin storage collection that is new in the
target version gets its shard inside the read-only process's catalog
savepoint, which is never committed, and the promoted leader allocates a
different one. So dataflows that hydrated while read-only are rebuilt at
cut-over, and anything reading a new collection cannot hydrate before
promotion.

On main this hits the three query-policy materialized views from #38762,
which are small leaves. If #40067's `mz_catalog_items` and #40843 on top
of it ship in one upgrade, the 12 catalog-server indexes that depend on
`mz_types` only hydrate after cut-over.

### Description

Reviewable commit by commit:

1. **Shards from the migration shard.** Builtin tables, sources and
materialized views without a shard get theirs from the builtin migration
shard, as `Replacement`-migrated collections do, and the read-only
process writes them the same way.
- An entry is only reused for the same `GlobalId` and builtin. A new
builtin's `GlobalId` exists only in the uncommitted savepoint, and a
later boot can give it to another builtin, for example after another
deploy generation was promoted.
- Versions without the new key field decode these entries and never use
them. Once released, the field must not be reverted or left out of a
backport, or the next version that has it panics on leftover entries.
2. **Leader clock.** For a collection the leader reports no frontier
for, such as a new builtin, the caught-up check compares against the
leader's clock instead of the current time. The clock is the upper of
`mz_cluster_replica_frontiers`, which the leader advances every second.
With the old leader down, as when a region is enabled again after a soft
delete, such a collection's inputs stop, so against the current time it
would lag forever.
3. **New builtins gate promotion.** Only a new storage collection
without a shard from the migration shard still seeds the caught-up
exclusion.
- New views and indexes no longer seed it. Otherwise a new view would
keep everything reading it out of the check, such as `mz_types` and its
indexes, which read #40843's new `mz_builtin_types`. So a new builtin
index over existing collections now has to hydrate before promotion.
- With the break-glass flag `enable_0dt_hydrate_migrated_builtin_mvs`
off, or a leader older than v26.17, every new builtin seeds it, as
before. New tables and sources are written either way.
4. **0dt workflow** `new-builtins-survive-promotion`. It and the two
`builtin-schema-migrations-*` workflows now wait until the replica
reports its reconciliation metrics, since a leader reports `IsLeader`
before it reconnects to its replicas.
5. **Stricter checks in that workflow.** It also compares the
`GlobalId`s of the collections read for the new builtins across the
promotion, because a replica only counts a dataflow as reused or
replaced if it had one with the same ids before. The wait for the
reconciliation metrics ends once two reads in a row agree.
6. **Rename** `migrate_replace` to `get_or_insert_shards`, since it now
also gets shards for collections that had none.
7. **Shorter leader-down run.** The workflow sets the caught-up check's
allowed lag to 10 s on the old leader before stopping it, so that it
only has to wait 20 s instead of 75 s.

The coverage of tables and sources, the matching by both `GlobalId` and
builtin, and the workflow come from Aljoscha's #40904, which fixes the
same bug.

### Verification

- New unit tests for the allocation and matching, the key encoding, and
the leader-clock comparison. Each fails when the behavior it covers is
reverted.
- The new workflow upgrades from v26.17.1, and from v26.47.1 with the
old leader stopped first, after it recorded a `REFRESH` materialized
view's frontier in the future. It checks that the new builtin
materialized views and sources were written on the read-only generation,
promotes, and checks that the collections read for them kept their
`GlobalId`s. With a running leader it also asserts that the catalog
server replaced no dataflow. With the old leader killed, a promotion can
replace dataflows that have nothing to do with new builtins, also on
main, so that run does not assert it. On main the workflow fails,
because the new builtin materialized views are not written on the
read-only generation.
- With #40067 and the PRs stacked on it (through #40900) merged in
locally, a 0dt upgrade from v26.51.0-rc.3 replaces no dataflow. Without
this PR the same upgrade replaces 23: the 12 catalog-server indexes that
read `mz_types`, the dataflows of the new collections, and user
dataflows that read the converted relations.
- Nightly (subsets):
https://buildkite.com/materialize/nightly/builds/18803 (upgrade and 0dt
jobs, on the first four commits) and
https://buildkite.com/materialize/nightly/builds/18805 (0dt jobs, on the
first five commits). On the final head, the new workflow and the two
`builtin-schema-migrations-*` workflows passed locally on the PR's CI
images.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
SangJunBak and others added 3 commits December 2, 2026 10:00
`mz_functions` and `mz_operators` became views, so the builtin version
pin check gets v26.54.0 as their conversion version.

The function relations get no migration step.
`migrate_builtin_item_types` drops the shard of a builtin that became a
view.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@SangJunBak
SangJunBak force-pushed the jun/function-relations branch from caf16d7 to fb7d43f Compare December 2, 2026 15:09

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants